package group2.beans;

import group2.core.database.IJpaCtrl;
import group2.core.database.JpaCtrlFactory;
import group2.core.entities.CamelUser;
import group2.core.entities.Post;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.NavigationHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;

/**
 * Used when adding posts
 * 
 * @author Christian
 */
@ManagedBean
@RequestScoped
public class AddPostControllerBean implements Serializable{

    @ManagedProperty(value = "#{addPostBackingBean}")
    private AddPostBackingBean apbb;
    
    private long lastPostId;
    private CamelUser user;
    

    public AddPostBackingBean getApbb() {
        return apbb;
    }

    public void setApbb(AddPostBackingBean apbb) {
        this.apbb = apbb;
    }
    
    public void doCreatePost(ActionEvent e) {

        Post p = new Post(0, apbb.getTitle(), apbb.getContent(), user);    
        IJpaCtrl<Post> ctrl = JpaCtrlFactory.getInstance().getPostCtrl();
        ctrl.create(p);
        setLastPostId(p.getId());
        
        
        apbb.setTitle("");
        apbb.setContent("");
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("/group2_dat076-camelblog_war_1.0-SNAPSHOT/jsf/showPost.jsf?postId=" + lastPostId);
        } catch (IOException ex) {
            Logger.getLogger(AddPostControllerBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public long getLastPostId() {
        return lastPostId;
    }

    public void setLastPostId(long lastPostId) {
        this.lastPostId = lastPostId;
    }
    

    /** Creates a new instance of AddPostControllerBean */
    public AddPostControllerBean() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session =
                (HttpSession) context.getExternalContext().getSession(true);
        user = (CamelUser) session.getAttribute("username");
    }
}
